'use strict';

const Service = require('egg').Service;

module.exports = class UserGroupService extends Service {
  // Update User Groups ///////////////////////////////////////////////////////////////////
  async updateUserGroup() {
    // Update --------------------------------
    if (this.ctx.request.query.act === 'update') {
      const arrID = this.ctx.request.body.id.split(',');
      const arrName = this.ctx.request.body.name.split(',');
      const arrView = this.ctx.request.body.view.split(',');
      const arrPost = this.ctx.request.body.post.split(',');
      const arrEdit = this.ctx.request.body.edit.split(',');
      const arrDelete = this.ctx.request.body.delete.split(',');
      const arrUpload = this.ctx.request.body.upload.split(',');
      for (let i = 0; i < arrID.length; i++) {
        // Check data
        arrID[i] = this.ctx.helper.checkInt(arrID[i]);
        arrName[i] = this.ctx.helper.trim(arrName[i]);
        arrView[i] = this.ctx.helper.checkInt(arrView[i]);
        arrPost[i] = this.ctx.helper.checkInt(arrPost[i]);
        arrEdit[i] = this.ctx.helper.checkInt(arrEdit[i]);
        arrDelete[i] = this.ctx.helper.checkInt(arrDelete[i]);
        arrUpload[i] = this.ctx.helper.checkInt(arrUpload[i]);

        // Skip Admin Group
        if (arrID[i] == 1) arrID[i] = -1;
        if (arrName[i].length < 1 || arrName[i].length > 50) arrID[i] = -1;
        if (arrView[i] < 0 || arrView > 3) arrID[i] = -1;
        if (arrPost[i] < 0 || arrPost > 2) arrID[i] = -1;
        if (arrEdit[i] < 0 || arrEdit > 2) arrID[i] = -1;
        if (arrDelete[i] < 0 || arrDelete > 2) arrID[i] = -1;
        if (arrUpload[i] < 0 || arrUpload > 1) arrID[i] = -1;

        // Update DB
        const arrData = { group_name: arrName[i],
          group_rights: String(arrView[i]) + String(arrPost[i]) + String(arrEdit[i]) + String(arrDelete[i]) + String(arrUpload[i]) };
        if (arrID[i] != -1) await this.ctx.app.connBlog.update('blog_usergroup', arrData, 'group_id=' + arrID[i]);
        // Insert new Group
        if (arrID[i] == 0) await this.ctx.app.connBlog.insert('blog_usergroup', arrData);
      }
      return;
    }

    // Delete --------------------------------
    if (this.ctx.request.query.act === 'delete') {
      if (!this.ctx.request.body.selected) return;
      let arrSelected = this.ctx.request.body.selected.split(',');
      for (let i = 0; i < arrSelected.length; i++) {
        arrSelected[i] = this.ctx.helper.checkInt(arrSelected[i]);
        if (arrSelected[i] < 1) {
          arrSelected.splice(i, 1);
          i--;
        }
      }
      if (arrSelected.length > 0) {
        arrSelected = arrSelected.join(',');
        await this.ctx.app.connBlog.doDelete('blog_user', 'user_groupID IN (' + arrSelected + ')');
        await this.ctx.app.connBlog.doDelete('blog_usergroup', 'group_id IN (' + arrSelected + ')');
      }
      return;
    }

  }
};
